package com.yiboshi.rehrs.util.js;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import com.yiboshi.rehrs.util.CacheUtils;
import com.yiboshi.rehrs.util.StrUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;

public class AesUtils {
    private static final String ALGORITHMS = "AES/ECB/PKCS5Padding";
    private static final String KEY_ALGORITHM = "AES";
    private static final Integer KEY_LENGTH = 128;
    public static String aesKey = "A3kppuf53Ch498Dj";
    public static String key;


    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    //加密
    public static String encrypt(String str, String str2) throws Exception {
        String key = str+str2;
        String byCache = CacheUtils.getByCache10Min(key, String.class);
        if(StrUtils.isNotBlank(byCache)){
            return byCache;
        }
        Cipher cipher =null;
        try{
            cipher = CipherPool.borrowCipher(ALGORITHMS);// Cipher.getInstance(ALGORITHMS);
            cipher.init(1, new SecretKeySpec(str2.getBytes(), KEY_ALGORITHM));
            byte[] doFinal = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
            //return Base64Encoder.encode(doFinal, doFinal.length);
            byCache =  Base64Encoder.encode(doFinal);
            CacheUtils.putByCache10Min(key, byCache);
            return  byCache;
        } finally {
            if (cipher != null) {
                CipherPool.returnCipher(cipher,ALGORITHMS);
            }
        }

    }

    public static String decrypt(String str, String str2) throws Exception {
        // byte[] decode = Base64.decode(str, 0);
        Cipher cipher =null;
        try{
            byte[] decode = Base64Decoder.decode(str);
            cipher =CipherPool.borrowCipher(ALGORITHMS);//;
            cipher.init(2, new SecretKeySpec(str2.getBytes(), KEY_ALGORITHM));
            return new String(cipher.doFinal(decode));
        } finally {
            if (cipher != null) {
                CipherPool.returnCipher(cipher,ALGORITHMS);
            }
        }
    }




}